package com.liuceng.mps.utils;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.SecureRandom;
import java.util.Random;
import java.util.UUID;

/**
 * IdChaosUtil.java 利用进制转换 进行数字混淆
 * 
 * @author liyuhang
 */
public abstract class ChaosUtils {
  private static final Logger LOG = LoggerFactory.getLogger(ChaosUtils.class);
  private static long CHAOS_FACTOR = 814611L;
  private static int HEX = 19;

  /**
   * 工具类无法实例化
   */
  private ChaosUtils() {
    super();
  }

  /**
   * 对字符串进行混淆，字符串必须是有效整数数字
   * 
   * @param id
   * @return
   */
  public static String chaos(String id) {
    if (StringUtils.isEmpty(id)) {
      return StringUtils.EMPTY;
    } else if (!NumberUtils.isNumber(id)) {
      return StringUtils.EMPTY;
    }
    return chaos(Long.valueOf(id));
  }

  /**
   * 对数字进行混淆
   * 
   * @param id
   * @return
   */
  public static String chaos(Long id) {
    if (null == id || id <= 0) {
      return StringUtils.EMPTY;
    }
    return Long.toString(id * CHAOS_FACTOR, HEX);
  }

  /**
   * 对字符串进行反混淆，解析错误返回null
   * 
   * @param id
   * @return
   */
  public static Long unChaos(String id) {
    Long result = null;
    try {
      if (StringUtils.isEmpty(id)) {
        return null;
      }
      Long value = Long.parseLong(id, HEX);
      result = value / CHAOS_FACTOR;
    } catch (Exception e) {
      LOG.error("unChaos error id:" + id, e);
      result = null;
    }
    return result;
  }

  /**
   * 生成lenc长度的随机字符串
   * 
   * @param len
   * @return
   */
  public static final String PROTOTYPE =
      "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

  public static String genRandomStr(int len) {
    char[] c = PROTOTYPE.toCharArray();
    Random random = new Random();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < len; i++) {
      sb.append(c[random.nextInt(c.length)]);
    }
    return sb.toString();
  }

  private static SecureRandom random = new SecureRandom();

  /**
   * 封装JDK自带的UUID, 通过Random数字生成, 中间有-分割.
   */
  public static String uuid() {
    return UUID.randomUUID().toString();
  }

  /**
   * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.
   */
  public static String uuid2() {
    return UUID.randomUUID().toString().replaceAll("-", "");
  }

  /**
   * 使用SecureRandom随机生成Long.
   */
  public static long randomLong() {
    return Math.abs(random.nextLong());
  }

  /**
   * 基于Base62编码的SecureRandom随机生成bytes.
   */
  public static String randomBase62(int length) {
    byte[] randomBytes = new byte[length];
    random.nextBytes(randomBytes);
    return EncodeUtils.encodeBase62(randomBytes);
  }

}
